package com.twb.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.twb.core.base.entity.TwbPageInfo;
import com.twb.core.base.service.impl.BaseService;
import com.twb.core.exception.ServiceException;
import com.twb.core.util.BeanUtils;
import com.twb.core.util.DateUtil;
import com.twb.core.util.TwbPageUtil;
import com.twb.system.entity.twbSequence.TwbSequence;
import com.twb.system.entity.twbSequence.dto.SearchTwbSequenceDto;
import com.twb.system.entity.twbSequence.vo.SaveTwbSequenceVo;
import com.twb.system.entity.twbSequence.vo.SearchTwbSequenceVo;
import com.twb.system.entity.twbSequence.vo.UpdateTwbSequenceByIdVo;
import com.twb.system.mapper.TwbSequenceMapper;
import com.twb.system.service.ITwbSequenceService;

/**
 * @author DSY
 * @ClassName TwbSequenceService
 * @Description 序列表service
 * @date 2020-12-24 14:55:12
 */
@Service("twbSequenceService")
public class TwbSequenceService extends BaseService<TwbSequenceMapper, TwbSequence> implements ITwbSequenceService {

  @Autowired
  TwbSequenceMapper twbSequenceMapper;

  @Override
  public TwbPageInfo<SearchTwbSequenceDto> searchTwbSequence(SearchTwbSequenceVo vo) {
    TwbPageUtil.startPage(vo);
    List<SearchTwbSequenceDto> list = twbSequenceMapper.searchTwbSequence(vo);
    return TwbPageUtil.of(list);
  }

  @Override
  public List<SearchTwbSequenceDto> searchTwbSequenceList(SearchTwbSequenceVo vo) {
    List<SearchTwbSequenceDto> list = twbSequenceMapper.searchTwbSequence(vo);
    return list;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int saveTwbSequence(SaveTwbSequenceVo vo) {

    TwbSequence checkVo = new TwbSequence();
    checkVo.setCode(vo.getCode()); // 此处需要修改为需要校验重复的字段
    checkVo.setIsdel(0);
    long count = this.count(checkVo);
    if (count > 0) {
      throw new ServiceException(String.format("[%s]已存在", checkVo.getName()));
    }

    TwbSequence record = new TwbSequence();
    BeanUtils.copyNotNullProperties(vo, record);
    record.setId(this.getUUID());
    this.setCreateInfo(record);
    this.setUpdateInfo(record);
    boolean result = this.save(record);
    if (result) {
      return 1;
    } else {
      return 0;
    }
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int updateTwbSequenceById(UpdateTwbSequenceByIdVo vo) {
    TwbSequence record = twbSequenceMapper.selectById(vo.getId());
    if (null == record) {
      throw new ServiceException("数据不存在");
    }

    if (!vo.getName().equalsIgnoreCase(record.getName())) {
      TwbSequence checkVo = new TwbSequence();
      checkVo.setName(vo.getName()); // 此处需要修改为需要校验重复的字段
      checkVo.setIsdel(0);
      long count = this.count(checkVo);
      if (count > 0) {
        throw new ServiceException(String.format("[%s]已存在", checkVo.getName()));
      }
    }

    BeanUtils.copyProperties(vo, record);
    this.setUpdateInfo(record);
    boolean result = this.updateById(record);
    if (result) {
      return 1;
    } else {
      return 0;
    }
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteTwbSequenceById(String id) {
    int result = twbSequenceMapper.deleteById(id);
    return result;
  }

  @Override
  public int deleteTwbSequenceByIds(String ids) {

    return twbSequenceMapper.deleteBatchIds(Arrays.asList(ids.split(",")));
  }

  @Override
  public int logicBatchDeleteTwbSequenceByIds(String ids) {
    List<String> list = new ArrayList<String>();
    Collections.addAll(list, ids.split(","));
    return twbSequenceMapper.logicBatchDeleteByIds(list);
  }

  @Override
  public int importExcel(Map<String, String> map) {
    System.out.println(map.toString());
    return 0;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  synchronized public String createCode(String code) {
    if (StringUtils.isBlank(code)) {
      throw new ServiceException("序列编码不能为空");
    }
    TwbSequence param = new TwbSequence();
    param.setCode(code);
    param.setIsdel(0);
    TwbSequence codeSeq = this.getOne(param);
    if (null == codeSeq) {
      throw new ServiceException("序列编码不存在");
    }

    //生成的序列号
    String codeSeqStr = null;

    //前缀
    String prefix = codeSeq.getPrefix() == null ? "" : codeSeq.getPrefix();
    //日期规则
    String dateRule = codeSeq.getDateRule();
    //分隔符
    String sepCode = codeSeq.getSplitCode() == null ? "" : codeSeq.getSplitCode();
    //序列位数
    Integer seqCount = codeSeq.getSeqCount();
    //序列步长
    Integer seqStep = codeSeq.getSeqStep();
    //下一个序列数
    Long seqNext = codeSeq.getSeqNext();
    //是否自动刷新
    Integer autoRefresh = codeSeq.getAutoRefresh();
    //当前序列编码
    String currentCode = codeSeq.getCurrentCode();
    //格式化日期
    String dateStr = "";
    if (StringUtils.isNotBlank(dateRule)) {
      dateStr = DateUtil.format(new Date(), dateRule);
    }
    //格式化序列字符串
    String seqStr = "1";
    if (null == seqNext) {
      seqNext = 1L;
    }
    //如果当前编码的日期和当前日期不同，并且开启了自动刷新，则序列号自动变成1
    if (StringUtils.isNotBlank(currentCode) && !currentCode.contains(dateStr) && autoRefresh == 1) {
      seqNext = 1L;
    }
    //如果当前序列数<序列位数，需要补0，否则直接取下一序列号
    if (seqCount > 0) {
      if (seqStr.length() < seqCount) {
        seqStr = String.format("%0" + seqCount + "d", seqNext);
      } else {
        seqStr = seqNext + "";
      }
    }

    codeSeqStr = prefix + sepCode + dateStr + sepCode + seqStr;

    //更新序列号
    codeSeq.setSeqNext(seqNext + seqStep);
    codeSeq.setCurrentCode(codeSeqStr);
    this.updateById(codeSeq);

    return codeSeqStr;
  }
}
